var gulp = require("gulp");

var gutil = require("gulp-util");
var cache = require("gulp-cached");
var less = require("gulp-less");
var autoprefixer = require('gulp-autoprefixer');
var webpack = require("webpack");
var webpackConfig = require("./webpack.config.js");
var debug = require('gulp-debug');
var WebpackDevServer = require("webpack-dev-server");
var livereload = require('gulp-livereload');
var remember = require('gulp-remember');
var connect = require('gulp-connect');

// 打包之前清除文件里的旧文件
gulp.task('clean', function() {
    gulp.src('dist/', {
        read: false
    })
    .pipe(clean());
});

/**
 * 监听less
 */
gulp.task('styles', function () {
    gulp.src('src/css/less/*.less')
    .pipe(cache('style'))
    .pipe(less())
    .on('error', handleLessError)
    .pipe(autoprefixer({
        browsers: ['last 3 version']
    }))
    .pipe(gulp.dest('src/css/'))
});

function handleLessError(err) {
    if (err.message) {
        console.log(err.message)
    } else {
        console.log(err)
    }
    this.emit('end')
}

/**
 * 开发环境
 */
gulp.task("webpack-dev-server", function(callback) {
    var myConfig = Object.create(webpackConfig);
    var compiler = webpack(myConfig);

    new WebpackDevServer(compiler, {
        // server and middleware options
    }).listen(1001, "localhost", function(err) {
        if(err) throw new gutil.PluginError("webpack-dev-server", err);
        // Server listening
        gutil.log("[webpack-dev-server]", "http://localhost:1001");
    });
});

var devConfig, devCompiler;
devConfig = Object.create(webpackConfig);
devConfig.devtool = "sourcemap";
devConfig.debug = true;
devCompiler = webpack(devConfig);
gulp.task('webpack', function(done) {
    devCompiler.run(function(err, stats) {
        if (err) {
          throw new gutil.PluginError("webpack:build-dev", err);
          return;
        }
        gutil.log("[webpack:build-dev]", stats.toString({
          colors: true
        }));
        done();
    });
});

//启动服务器
gulp.task("connect", function() {
    connect.server({
        port: 1001,
        livereload: true
    });
});

/**
 * 监控文件
 */
gulp.task("watch", function(callback) {
    gulp.watch(['src/**'], ['webpack'])
    .on('end', callback);
    gulp.watch('src/css/less/**', ['styles'])
    .on('end', callback);
});

gulp.task('default',['styles', 'webpack', 'connect', 'watch']);













